﻿using AutoMapper;
using MediatR;
using SmartCity.EventHandle.API.Read.Application.Commands;
using SmartCity.EventHandle.API.Read.DTO;
using SmartCity.EventHandle.Domain;
using SmartCity.EventHandle.Errorcode;
using SmartCity.EventHandle.Infrastructure.Commons;
using SmartCity.EventHandle.Infrastructure.Extensions;
using SmartCity.EventHandle.Infrastructure.Interfraces;

namespace SmartCity.EventHandle.API.Read.Application.CommandHandlers
{
    /// <summary>
    /// 我的代办查询命令处理
    /// </summary>
    public class MyPendingQueryCommandHandler:IRequestHandler<MyPendingQueryCommand,ApiResult<List<InstanceDto>>>
    {
        private readonly IBaseRepository<WF_Instance> instanceRep;
        private readonly IMapper mapper;

        public MyPendingQueryCommandHandler(IBaseRepository<WF_Instance> instanceRep,IMapper mapper)
        {
            this.instanceRep = instanceRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回代办列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<List<InstanceDto>>> Handle(MyPendingQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<InstanceDto>> result = new ApiResult<List<InstanceDto>>();
            result.code = ApiEnum.SearchSuccess;
            result.message = ApiEnum.SearchSuccess.GetDescription();

            //List<WF_Instance> list = new List<WF_Instance>();
            //if(request.RoleId == 1)
            //{
            //    //超级管理员可以查看所有代办
            //    list = instanceRep.GetAll().Where(x=>x.FlowState < (int)FlowStatus.FiniShed).ToList();
            //}
            //else
            //{
            //    //审批人员
            //    list = instanceRep.GetAll().Where(x => x.NextOperatorId == request.UserId && x.FlowState < (int)FlowStatus.FiniShed).ToList();
            //}
            var list = instanceRep.GetAll().Where(x => x.FlowState < (int)FlowStatus.FiniShed);
            if(request.RoleId != 1)
            {
                list = instanceRep.GetAll().Where(x=>x.NextOperatorId == request.UserId);
            }

            if(!string.IsNullOrEmpty(request.CreatedDate))
            {
                list = list.Where(x => x.CreateTime.ToString().Substring(0,10) == request.CreatedDate);
            }
            
            result.data = mapper.Map<List<InstanceDto>>(list);

            return Task.FromResult(result);
        }
    }
}
